package com.lin.manager.sms.factory;

import com.lin.manager.sms.enums.PlatformEnum;
import com.lin.manager.sms.enums.SendEnum;
import com.lin.manager.sms.ex.CustomSendException;
import com.lin.manager.sms.model.Sms;
import com.lin.manager.sms.strategy.SendStrategy;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author linjiang
 * @date 2024/8/19
 * @fn 短信工厂
 */
public class SmsFactory {
    private Sms sms;

    private Map<PlatformEnum, SendStrategy> strategyMap;

    public SmsFactory(Sms sms) {
        this.sms = sms;
    }

    /**
     * 添加短信策略
     *
     * @param strategies
     */
    public void addStrategy(List<SendStrategy> strategies) {
        if (Objects.isNull(this.strategyMap)) {
            this.strategyMap = new HashMap<>();
        }

        strategies.stream().forEach(strategy ->
                strategyMap.put(strategy.getPlatform(), strategy));
    }

    /**
     * 短信配置发送变化，工厂需要重新定义
     *
     * @param sms
     */
    public void setSms(Sms sms) {
        this.sms = sms;
    }

    public Sms getSms() {
        return sms;
    }

    /**
     * 获取短信发送策略
     *
     * @return
     */
    public SendStrategy getSendStrategy() {
        // 确认短信平台
        PlatformEnum platform = getPlatform();
        if (Objects.nonNull(strategyMap)) {
            SendStrategy strategy = strategyMap.get(platform);
            if (Objects.nonNull(strategy)) {
                return strategy;
            }
        }

        throw new CustomSendException(SendEnum.SEND_SERVICE_NOT_EXIST);
    }

    private PlatformEnum getPlatform() {
        if (Objects.isNull(sms)) {
            throw new CustomSendException(SendEnum.SEND_PLATFORM_PARAM_EX);
        }

        String platform = sms.getPlatform();
        if (!StringUtils.hasText(platform)) {
            throw new CustomSendException(SendEnum.SEND_PLATFORM_NOT_EXIST);
        }

        PlatformEnum platformEnum = PlatformEnum.get(platform);
        if (Objects.isNull(platformEnum)) {
            throw new CustomSendException(SendEnum.SEND_PLATFORM_NOT_EXIST);
        }

        return platformEnum;
    }

}
